<template>
  <!-- 分类组件 -->
  <Category :isShow="contentShow"></Category>
  <!-- 展示组件 -->
  <el-card style="margin: 10px 0px">
    <!-- Spu数据展示列表 -->
    <div v-show="contentShow === 0">
      <el-button type="primary" icon="Plus" :disabled="!thirdCateId" @click="addSpuInfo"
        >添加SPU</el-button
      >
      <el-table :data="hasSpuArr" style="margin: 10px 0px" border>
        <el-table-column type="index" label="序号" align="center" width="100px">
        </el-table-column>
        <el-table-column prop="spuName" label="SPU名称" align="center"> </el-table-column>
        <el-table-column prop="description" align="center" label="SPU描述">
        </el-table-column>
        <el-table-column label="SPU操作" align="center">
          <template #="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="Plus"
              title="添加SKU"
              @click="addSku(row)"
            ></el-button>
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              title="修改SPU"
              @click="editSpuInfo(row)"
            ></el-button>
            <el-button
              type="info"
              size="small"
              icon="View"
              title="查看SKU列表"
              @click="findSkuList(row)"
            ></el-button>
            <el-popconfirm
              :title="`确定删除【${row.spuName}】吗？`"
              @confirm="deleteSpu(row)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  icon="Delete"
                  title="删除SKU"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        background
        :page-sizes="[10, 20, 50]"
        layout="->, prev, pager, next, sizes, jumper, total"
        :total="total"
        @current-change="curPageChange"
        @size-change="pageSizeChange"
      >
      </el-pagination>
    </div>
    <!-- Spu数据添加和修改 -->
    <SpuForm
      ref="spuFormRef"
      v-show="contentShow === 1"
      @updateContentShow="changeScene"
    ></SpuForm>
    <!-- Sku数据的添加 -->
    <SkuForm
      ref="skuFormRef"
      v-show="contentShow === 2"
      @updateContentShow="changeScene"
    ></SkuForm>
    <!-- Sku列表 -->
    <el-dialog v-model="showDialog" title="SKU列表">
      <el-table :data="skuList">
        <el-table-column type="index" label="序号" width="100px"> </el-table-column>
        <el-table-column prop="skuName" label="SKU名称"> </el-table-column>
        <el-table-column prop="price" label="SKU价格"> </el-table-column>
        <el-table-column prop="weight" label="SKU重量"> </el-table-column>
        <el-table-column label="SKU图片">
          <template #="{ row }">
            <img
              :src="row.skuDefaultImg"
              style="width: 100px; height: 100px"
              alt="暂无图片"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from "vue";
import { storeToRefs } from "pinia";
import { reqHasSpu, reqSkuListBySpuId, reqDeleteSpu } from "@/api/product/spu";
import type { SkuAddObj, SpuObj } from "@/api/product/spu/types";
import { ElMessage } from "element-plus";
import SpuForm from "./spuForm.vue";
import SkuForm from "./skuForm.vue";
import { useCategoryStore } from "@/store/modules/category";
// 分类仓库对象
const categoryStore = useCategoryStore();
// 解构赋值
const { thirdCateId } = storeToRefs(categoryStore);
// 控制分类组件的禁用
const contentShow = ref(0);
// 当前页
const currentPage = ref(1);
// 页面展示数据的条数
const pageSize = ref(10);
// 数据的总条数
const total = ref(0);
// 已有Spu数据
const hasSpuArr = ref<SpuObj[]>([]);
// 子组件SpuForm的实例
const spuFormRef = ref();
// 子组件SkuForm的实例
const skuFormRef = ref();
// Sku列表数据
const skuList = ref<SkuAddObj[]>([]);
// 控制Sku展示列表的显示和隐藏
const showDialog = ref(false);
// 监听三级分类id的变化
watch(thirdCateId, (newValue) => {
  // 三级分类id变化，发送请求获取Spu数据
  // 但要保证三级分类id数据不为空，才发送请求
  if (!newValue) return;
  getHasSpu();
});
// 获取已有Spu数据
const getHasSpu = async (page = 1) => {
  // 不传当前页的话，当前页为第一页；传递的话，则为传递的页数
  // 为了页面展示条数改变时，当前页为第一页
  currentPage.value = page;
  let result = await reqHasSpu(currentPage.value, pageSize.value, thirdCateId.value);
  if (result?.code === 200) {
    hasSpuArr.value = result.data?.records;
    total.value = result.data.total;
  } else {
    ElMessage.error("获取数据失败");
  }
};
// 当前页改变事件回调
const curPageChange = () => {
  getHasSpu(currentPage.value);
};
// 页面展示数据改变事件回调
const pageSizeChange = () => {
  getHasSpu();
};
// 添加SPU按钮事件回调
const addSpuInfo = () => {
  // 切换到新增页面
  contentShow.value = 1;
  // 调用子组件方法初始化数据
  spuFormRef.value.addSpuInitData(categoryStore.thirdCateId);
};
// 修改SPU按钮事件回调
const editSpuInfo = (row: SpuObj) => {
  // 切换到编辑页面
  contentShow.value = 1;
  // 编辑数据时，数据要回显，编辑页面需要的数据在这处理
  /*
    子组件的数据和数据操作方法最好在子组件内，
      使用 ref 获取子组件实例，调用方法，避免父传子，麻烦
  */
  spuFormRef.value.updateSpuInitData(row);
};
// 自定义事件：改变场景
const changeScene = (num: number, flag?: boolean) => {
  contentShow.value = num;
  // 再次获取Spu
  if (flag === true) {
    // 修改数据成功，留在当前页
    getHasSpu(currentPage.value);
  }
  if (flag === false) {
    // 新增数据成功，跳转第一页
    getHasSpu();
  }
};
// 添加Sku按钮的回调
const addSku = (row: SpuObj) => {
  // 切换场景
  contentShow.value = 2;
  // 初始化添加Sku页面的数据（使用ref调用Sku组件中的方法）
  skuFormRef.value.addSkuInitData(
    row,
    categoryStore.primCateId,
    categoryStore.secCateId,
    categoryStore.thirdCateId
  );
};
// 查看某个Spu的Sku列表
const findSkuList = async (row: SpuObj) => {
  showDialog.value = true;
  let result = await reqSkuListBySpuId(row.id as number);
  if (result?.code) {
    // 存储数据
    skuList.value = result?.data;
  } else {
    ElMessage.error("Sku列表获取失败");
  }
};
// 删除Spu
const deleteSpu = async (row: SpuObj) => {
  // 发送请求删除Spu
  let result = await reqDeleteSpu(row.id as number);
  if (result?.code === 200) {
    ElMessage.success("SPU删除成功");
    // 重新获取Spu列表
    if (hasSpuArr.value.length > 0) {
      getHasSpu();
    } else {
      getHasSpu(currentPage.value - 1);
    }
  } else {
    ElMessage.error("Spu删除失败");
  }
};
// 离开组件时，清空分类组件的数据
onBeforeUnmount(() => {
  categoryStore.$reset();
});
</script>

<style scoped></style>
